//
//  SISSHomeViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/13.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHomeViewController.h"
#import "SISSHomeFunctionView.h"
#import "SISSMapViewController.h"
#import "SISSHomeSearchView.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSBaseTableView.h"
#import "SISSScrollView.h"
#import "SISSHomeHousingViewController.h"
#import "SISSHomePassengerViewController.h"
#import "SISSHomeRentOutViewController.h"
#import "SISSHomeTenantViewController.h"
#import "SISSFindHouseResourcesViewController.h"
#import "SISSFindPassengerResourceViewController.h"
#import "SISSFindCooperationViewController.h"
#import "SISSFindRentOutViewController.h"
#import "SISSFindTenantViewController.h"
#import "SISSFindNewHouseViewController.h"
#import "SISSSearchViewController.h"
#import "SISSChooseCityViewController.h"
#import "SISSHousePriceMapViewController.h"
#import "SISSScanViewController.h"

#import "SISSBaseWebViewController.h"
#import "SISSHouseRegistSuccessViewController.h"

#define TopViewHeight 239
static NSString * const collectionViewCellReuseID = @"collectionViewCellReuseID";

@interface SISSHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SISSHomeFunctionViewDelegate,SISSHomeHousingViewControllerDelegate,SISSHomePassengerViewControllerDelegate,UIGestureRecognizerDelegate,SISSHomeSearchViewDelegate>

/** 标题view */
@property(nonatomic,weak) UIView *titleView;
/** flowLayout */
@property (weak, nonatomic) UICollectionViewFlowLayout *flowLayout;
/** 内容的view */
@property(nonatomic,weak) UICollectionView *collectionView;
/** 最新房源 */
@property (weak, nonatomic) SISSHomeHousingViewController *homeHousingViewController;
/** 最新客源 */
@property (weak, nonatomic) SISSHomePassengerViewController *homePassengerViewController;
/** 最新出租 */
@property (weak, nonatomic) SISSHomeRentOutViewController *homeRentOutViewController;
/** 最新租客 */
@property (weak, nonatomic) SISSHomeTenantViewController *homeRenantViewController;
/** headView */
@property (weak, nonatomic) UIView *headView;
/** 线条 */
@property (weak, nonatomic) UIView *lineView;
/** 记录选中按钮状态 */
@property (weak, nonatomic) UIButton *selectedButton;
/* 存储最新选择按钮 */
@property (strong, nonatomic) NSMutableArray<UIButton *> *buttonArrM;

/* 拖拽手势 */
@property (strong, nonatomic) UIPanGestureRecognizer *panGesture;

/* searchBar */
@property (weak, nonatomic) SISSHomeSearchView *searchBar;
@property (weak, nonatomic) SISSHomeSearchView *searchView;

/* offset */
@property (assign, nonatomic) CGFloat offset;


@end

@implementation SISSHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.offset = 0;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 一定要在viewDidAppear里面设置itemSize;只有在该方法里面才能拿到真是的frame
    self.flowLayout.itemSize = self.collectionView.bounds.size;
   
}

- (void)viewWillLayoutSubviews {
    
    [super viewWillLayoutSubviews];
    
    self.flowLayout.itemSize = self.collectionView.bounds.size;
}


#pragma mark - 代理
#pragma mark -- SISSHomeSearchViewDelegate
- (void)chooseCityButtonClickAction {
    
//    SISSChooseCityViewController *vc = [SISSChooseCityViewController new];
//    vc.title = @"选择城市";
//    vc.selectCompleteBlock = ^(NSString *city) {
//        self.searchView.city = city;
//        self.searchBar.city = city;
//    };
//    [self.navigationController pushViewController:vc animated:YES];
    
//    SISSHouseRegistSuccessViewController *vc = [SISSHouseRegistSuccessViewController new];
//    vc.isCooperation = YES;
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)qrcodeButtonClickAction {
    
    SISSScanViewController *vc = [[SISSScanViewController alloc] init];
    //设置扫码区域参数
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    style.centerUpOffset = 44;
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Inner;
    style.photoframeLineW = 2;
    style.photoframeAngleW = 18;
    style.photoframeAngleH = 18;
    style.isNeedShowRetangle = YES;
    
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    style.animationImage = [UIImage imageNamed:@"qrcode_Scan_Line"];
    style.colorAngle = [UIColor colorWithRed:0./255 green:200./255. blue:20./255. alpha:1.0];
    //非正方形
    //设置矩形宽高比
//    style.whRatio = 4.3/2.18;
//    //离左边和右边距离
//    style.xScanRetangleOffset = 30;
    
    style.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    
    vc.style = style;
    vc.isOpenInterestRect = YES;
    vc.libraryType = SLT_Native;
    vc.scanCodeType = SCT_QRCode;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- SISSHomeFunctionViewDelegate 功能按钮点击事件
- (void)homeFunctionButtonClickAtIndex:(NSInteger)index {
    
    if (index == 0) {
        
        SISSFindHouseResourcesViewController *vc = [[SISSFindHouseResourcesViewController alloc] init];
        vc.title = @"找房源";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 1) {
        
        SISSFindPassengerResourceViewController *vc = [[SISSFindPassengerResourceViewController alloc] init];
        vc.title = @"找客源";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 2) {
        
        SISSFindCooperationViewController *vc = [[SISSFindCooperationViewController alloc] init];
        vc.title = @"找合作";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 3) {
        
        SISSMapViewController *mapVC = [[SISSMapViewController alloc] init];
        
        [self.navigationController pushViewController:mapVC animated:YES];
    } else if (index == 4) {
        SISSBaseWebViewController *vc = [[SISSBaseWebViewController alloc] init];
        vc.title = @"买房百科";
        vc.url = @"#!/wiki";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 5) {
        
        SISSFindRentOutViewController *vc = [[SISSFindRentOutViewController alloc] init];
        vc.title = @"找出租";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 6) {
        
        SISSFindTenantViewController *vc = [[SISSFindTenantViewController alloc] init];
        vc.title = @"找租客";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 7) {
        
        SISSFindNewHouseViewController *vc = [[SISSFindNewHouseViewController alloc] init];
        vc.title = @"找新房";
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (index == 8) {
        
        SISSHousePriceMapViewController *vc = [[SISSHousePriceMapViewController alloc] init];
        vc.title = @"房价地图";
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


#pragma mark -- UIGestureRecognizerDelegate 支持多手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    [self buttonClick:self.buttonArrM[index]];
}


#pragma mark -- UICollectionViewDataSource & UICollectionViewDelegate 最新房源、客源

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellReuseID forIndexPath:indexPath];
    
    if (indexPath.item == 0) {
        
        SISSHomeHousingViewController *homeHousingViewController = [[SISSHomeHousingViewController alloc] init];
        [self addChildViewController:homeHousingViewController];
        self.homeHousingViewController = homeHousingViewController;
        homeHousingViewController.isForbiddenBlock = ^(BOOL isForbidden) {
            self.panGesture.enabled = !isForbidden;
        };
        [cell.contentView addSubview:homeHousingViewController.tableView];
        homeHousingViewController.view.frame = cell.contentView.frame;
        
    } else if (indexPath.item == 1) {
        cell.contentView.backgroundColor = [UIColor yellowColor];
        SISSHomePassengerViewController *homePassengerViewController = [[SISSHomePassengerViewController alloc] init];
        [self addChildViewController:homePassengerViewController];
        self.homePassengerViewController = homePassengerViewController;
        homePassengerViewController.isForbiddenBlock = ^(BOOL isForbidden) {
            self.panGesture.enabled = !isForbidden;
        };
        [cell.contentView addSubview:homePassengerViewController.tableView];
        homePassengerViewController.view.frame = cell.contentView.frame;
    } else if (indexPath.item == 2) {
        cell.contentView.backgroundColor = [UIColor yellowColor];
        SISSHomeRentOutViewController *homeRentOutViewController = [[SISSHomeRentOutViewController alloc] init];
        [self addChildViewController:homeRentOutViewController];
        self.homeRentOutViewController = homeRentOutViewController;
        homeRentOutViewController.isForbiddenBlock = ^(BOOL isForbidden) {
            self.panGesture.enabled = !isForbidden;
        };
        [cell.contentView addSubview:homeRentOutViewController.tableView];
        homeRentOutViewController.view.frame = cell.contentView.frame;
    } else if (indexPath.item == 3) {
        cell.contentView.backgroundColor = [UIColor yellowColor];
        SISSHomeTenantViewController *homeRenantViewController = [[SISSHomeTenantViewController alloc] init];
        [self addChildViewController:homeRenantViewController];
        self.homeRenantViewController = homeRenantViewController;
        homeRenantViewController.isForbiddenBlock = ^(BOOL isForbidden) {
            self.panGesture.enabled = !isForbidden;
        };
        [cell.contentView addSubview:homeRenantViewController.tableView];
        homeRenantViewController.view.frame = cell.contentView.frame;
    }
    
    return cell;
}

#pragma mark - 点击事件
#pragma mark -- 点击搜索视图响应事件
- (void)tapGestureAction:(UITapGestureRecognizer *)tap {
    
    SISSSearchViewController *vc = [[SISSSearchViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:NO completion:nil];
}

#pragma mark -- 手势点击事件
- (void)panGestureAction:(UIPanGestureRecognizer *)panGesture {
    // 1. 获取手势拖拽的位移值 (移动了多少) (针对最初触摸点进行计算)
    CGPoint translation = [panGesture translationInView:panGesture.view];
    
    // 2. 要重置位移计算的初始值
    [panGesture setTranslation:CGPointZero inView:panGesture.view];
    
    // 3.1 取到每次位移的y值, 更新约束
    // 计算新的高度值, 触发手势事件时, autolayout已经生效, 才能使用height来获取高度
    //    CGFloat height = self.headView.bounds.size.height + translation.y;
    // 4.1 计算透明度的值
    CGFloat alpha = (- self.offset)/TopViewHeight;
//    NSLog(@"  %f",alpha);
    CGPoint velocity = [panGesture velocityInView:panGesture.view];
    if (velocity.y < 0 && alpha < 0.95) {
//        NSLog(@"上上上");
        self.homeHousingViewController.canScroll = NO;
        self.homePassengerViewController.canScroll = NO;
        self.headView.alpha = 1 - alpha;
    } else {
//        NSLog(@"下下下");
        if (alpha > 0.6) {
            self.headView.alpha = 1 - alpha;
        } else {
            self.headView.alpha = 1 - alpha;
        }
        self.homeHousingViewController.canScroll = YES;
        self.homePassengerViewController.canScroll = YES;
    }


    self.offset += translation.y;
    
    if (self.offset < -TopViewHeight) {
        self.offset = -TopViewHeight;
    }
    
    if (self.offset > 0) {
        self.offset = 0;
    }
    
    self.flowLayout.itemSize = self.collectionView.bounds.size;
    WeakSelf
    [self.headView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(weakSelf.offset);
    }];
    
    self.searchView.alpha = alpha;
}

#pragma mark -- 最新房源和最新可以按钮点击事件
- (void)buttonClick:(UIButton *)button {
    
    if (button != self.selectedButton) {
        
        self.selectedButton.selected = NO;
        self.selectedButton = button;
    }
    
    self.selectedButton.selected = YES;
    WeakSelf
    if (button.tag == 1) {
        [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view.mas_centerX).offset(-6 * MAIN_SCALE);
        }];
        [self.homePassengerViewController requestNewestPassengerResourceData];
    } else if (button.tag == 0)  {
        [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view.mas_centerX).offset(-12 * MAIN_SCALE - weakSelf.buttonArrM[1].bounds.size.width);
        }];
        [self.homeHousingViewController requestNewestHouseResourceData];
    } else if (button.tag == 2)  {
        [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view.mas_centerX).offset(weakSelf.buttonArrM[2].bounds.size.width + 2 * MAIN_SCALE);
        }];
        [self.homeRentOutViewController requestNewestRentOutResourceData];
    } else if (button.tag == 3)  {
        [self.lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view.mas_centerX).offset(weakSelf.buttonArrM[2].bounds.size.width * 2 + 8 * MAIN_SCALE);
        }];
        [self.homeRenantViewController requestNewestRenantResourceData];
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:button.tag inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}




#pragma mark - UI & 布局
/**
 设置子视图
 */
- (void)setupSubviews {
    [super setupSubviews];
    
    // headView
    UIView *headView = [[UIView alloc] init];
    self.headView = headView;
    [self.view addSubview:headView];
    // 顶部背景视图
    UIView *bgView = [[UIView alloc] init];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
    [bgView addSubview:imageView];
    
    [self.headView addSubview:bgView];

    // 搜索框
    SISSHomeSearchView *searchBar = [[SISSHomeSearchView alloc] init];
    searchBar.delegate = self;
    [bgView addSubview:searchBar];
    self.searchBar = searchBar;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    [searchBar addGestureRecognizer:tap];
    
    // 功能按钮视图
    SISSHomeFunctionView *functionView = [[SISSHomeFunctionView alloc] init];
    functionView.delegate = self;
    
    [self.headView addSubview:functionView];
    
    // 标题栏
    UIView *titleView =[[UIView alloc]init];
    titleView.backgroundColor = [UIColor whiteColor];
    _titleView = titleView;
    [self.view addSubview:titleView];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = MAIN_COLOR;
    self.lineView = lineView;
    [self.view addSubview:lineView];
    
    UIView *titleViewBottomLine = [[UIView alloc] init];
    titleViewBottomLine.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [titleView addSubview:titleViewBottomLine];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout = flowLayout;
    
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellReuseID];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.pagingEnabled = YES;
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    for (int i = 0; i < 4; i++) {
        UIButton *button = [[UIButton alloc] init];
        [button setTitleColor:COLOR(0x8998A5) forState:UIControlStateNormal];
        [button setTitleColor:MAIN_COLOR forState:UIControlStateSelected];
        
        if ([SISSPublicSingleton shared].screenWidth < 350) { // 4英寸
            button.titleLabel.font = [UIFont systemFontOfSize:16];
        }
        
        if (i == 1) {
            [self.buttonArrM insertObject:button atIndex:0];
        } else {
            [self.buttonArrM addObject:button];
        }
        button.tag = i == 0 ? 1 : (i == 1 ? 0 : i); // 解决titleView的第1、2个横线的位置问题
        [titleView addSubview:button];
        
        if (i == 0) {
            [button setTitle:@"最新客源" forState:UIControlStateNormal];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(titleView.mas_centerX).offset(-3 * MAIN_SCALE);
                make.centerY.equalTo(titleView);
            }];
        } else if (i == 1) {
            button.selected = YES;
            self.selectedButton = button;
            [button setTitle:@"最新房源" forState:UIControlStateNormal];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.buttonArrM[1].mas_left).offset(-6 * MAIN_SCALE);
                make.centerY.equalTo(titleView);
            }];
        } else if (i == 2) {

            [button setTitle:@"最新出租" forState:UIControlStateNormal];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleView.mas_centerX).offset(3 * MAIN_SCALE);
                make.centerY.equalTo(titleView);
            }];
        } else {
            [button setTitle:@"最新租客" forState:UIControlStateNormal];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.buttonArrM[2].mas_right).offset(6 * MAIN_SCALE);
                make.centerY.equalTo(titleView);
            }];
        }
        
        // 添加点击事件
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // 自动布局
    CGFloat headerH = 226 + 84;
    CGFloat bgViewHeight = 136;
    CGFloat margin = 8;
    CGSize searchBarSize = CGSizeMake(318, 36);
//    CGFloat funcViewHeight = 82;
    CGFloat titleViewH = 47;
    CGSize lineSize = CGSizeMake(66, 3);
    CGFloat lineOffset = 75;
    if ([SISSPublicSingleton shared].screenWidth < 350) { // 4英寸
        lineSize.width = 60;
        lineOffset = 68;
    }
    
    WeakSelf
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
        make.height.equalTo(@(headerH));
    }];
    
    
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.mas_bottom).offset(8);
        make.left.right.equalTo(weakSelf.view);
        make.height.equalTo(@(titleViewH));
    }];
    
    [titleViewBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(titleView);
        make.bottom.equalTo(titleView).offset(-1);
        make.height.mas_equalTo(1);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleView);
        make.right.equalTo(weakSelf.view.mas_centerX).offset(-12 * MAIN_SCALE - lineOffset);
        make.size.mas_equalTo(lineSize);
    }];

    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.headView);
        make.height.mas_equalTo(bgViewHeight);
    }];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bgView);
    }];
    
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.bottom.equalTo(bgView).offset(-margin * 4);
        make.size.mas_equalTo(searchBarSize);
    }];
    
    [functionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.headView);
        make.top.equalTo(bgView.mas_bottom);
//        make.height.mas_equalTo(funcViewHeight);
        make.bottom.equalTo(weakSelf.headView);
    }];
    
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-kTabBarHeight);
    }];
    

    /*------ 添加拖拽手势 ------*/
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
    // 通过代理, 解决多个手势同时响应
    pan.delegate = self;
    self.panGesture = pan;
    // 添加到self.view上, 整个界面都能响应拖拽手势
    [self.view addGestureRecognizer:pan];
    
    // 搜索框
    SISSHomeSearchView *searchView = [[SISSHomeSearchView alloc] initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, 36)];
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.delegate = self;
    searchView.alpha = 0;
    [self.view addSubview:searchView];
    self.searchView = searchView;
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
    [searchView addGestureRecognizer:tap1];
}


#pragma mark - 懒加载
- (NSMutableArray<UIButton *> *)buttonArrM {
    if (!_buttonArrM) {
        _buttonArrM = [NSMutableArray arrayWithCapacity:4];
    }
    return _buttonArrM;
}

@end
